package com.qidian.buy.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qidian.buy.entity.Content;
import com.qidian.buy.content.mapper.ContentMapper;
import com.qidian.buy.content.service.IContentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qidian.buy.util.JSONTools;
import com.qidian.buy.util.pojo.BuyResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 戴着假发的程序员
 * @since 2023-05-18
 */
@Service
public class ContentServiceImpl extends ServiceImpl<ContentMapper, Content> implements IContentService {

    private List<Timer> timers = new ArrayList<>();

    @Value("${content-type.lunbo}")
    private int lunbo;
    @Value("${content-type.youxuanbimai}")
    private int youxuanbimai;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private ContentMapper contentMapper;
    @Override
    public BuyResult saveContent(Content content) {
        // 补全数据
        content.setCreated(new Date());
        content.setUpdated(new Date());
        int result = contentMapper.insert(content);
        if(result == 1){
            //  清理对应的缓存
            String key = "PORTAL_" + content.getCategoryId();
            stringRedisTemplate.delete(key);
            // 延迟一会再删 使用定时任务处理
            // (这里可以使用线程池处理)
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    // 再删一次
                    stringRedisTemplate.delete(key);
                    // timer也删除
                    timers.remove(timer);
                }
            },1000);
            // 将timer方法timers集合，目的是为了保存引用
            timers.add(timer);
        }
        return result ==1?BuyResult.ok():BuyResult.fal();
    }

    @Override
    public BuyResult<Content> queryContentByPage(Long catId, int page, int limit) {
        BuyResult<Content> result = new BuyResult<>();
        // 查询条数
        QueryWrapper<Content> wrapper = new QueryWrapper<>();
        wrapper.eq(catId!= -1,"category_id",catId);
        Long total = contentMapper.selectCount(wrapper);
        result.setCode(0);
        result.setMsg("");
        result.setCount(total);
        // 查询数据
        IPage<Content> pager = new Page<>();
        pager.setCurrent(page);
        pager.setSize(limit);
        pager = contentMapper.selectPage(pager,wrapper);
        result.setData(pager.getRecords());
        return result;
    }

    @Override
    public BuyResult queryPortal() {
        // 准备一个map放所有的数据
        Map data = new HashMap();
        // 查询轮播图，是要根据类别编号查询的。
        List<Content> lunboList = null;
        // 先查询缓存
        String key = "PORTAL_"+lunbo;
        String json = stringRedisTemplate.opsForValue().get(key);
        if(json != null && !"".equals(json)){
            try {
                lunboList = JSONTools.json2list(json,Content.class);
            } catch (Exception e) {
                lunboList = null;
            }
        }
        QueryWrapper<Content> wrapper = new QueryWrapper<>();
        if(lunboList == null) {// 缓存没有查询到 就查询数据库
            wrapper.eq("category_id", lunbo);
            lunboList = contentMapper.selectList(wrapper);
            // 给缓存放一份
            stringRedisTemplate.opsForValue().set(key,JSONTools.object2json(lunboList));
            // 设置存活时间
            stringRedisTemplate.expire(key,30+(new Random().nextInt(30)), TimeUnit.MINUTES);
        }
        // 给data中设置数据
        data.put("lunbo",lunboList);
        // 查询优选必买
        // 一样的处理方式
        key = "PORTAL_" + youxuanbimai;
        List<Content> youxuanbimaiList = null;
        json = stringRedisTemplate.opsForValue().get(key);
        if(json != null && !"".equals(json)){
            try {
                youxuanbimaiList = JSONTools.json2list(json,Content.class);
            } catch (Exception e) {
                youxuanbimaiList = null;
            }
        }
        if(youxuanbimaiList == null){
            wrapper = new QueryWrapper<>();
            wrapper.eq("category_id",youxuanbimai);
            youxuanbimaiList = contentMapper.selectList(wrapper);
            stringRedisTemplate.opsForValue().set(key,JSONTools.object2json(youxuanbimaiList));
            stringRedisTemplate.expire(key,30+(new Random().nextInt(30)), TimeUnit.MINUTES);
        }
        data.put("youxuanbimai",youxuanbimaiList);
        return BuyResult.ok(data);
    }
}
